//
//  OrderScoreServiceViewController.m
//  customer
//
//  Created by Holothurian on 2018/11/10.
//  Copyright © 2018年 yinlong. All rights reserved.
//

#import "OrderScoreServiceViewController.h"
#import "OneKeyRepairUploadImageCollectionCell.h"
#import "OneKeyRepairMainTableCell.h"
#import "OrderScoreStarTableViewCell.h"
#import "MyOrderDetailViewController.h"
#import "MyOrderBaseViewController.h"
#import "MyOrderSearchViewController.h"

static NSString *UploadImageCellIdentifier = @"UploadImageCellIdentifier";
static NSString *QuestionCellIdentifier = @"QuestionCellIdentifier";
static NSString *StarCellIdentifier = @"StarCellIdentifier";
static NSString *QuestionPlaceholder = @"写下您的评价吧";
@interface OrderScoreServiceViewController ()<UITableViewDelegate,UITableViewDataSource,UITextViewDelegate,OneKeyRepairUploadImageTableCellDelegate,TZImagePickerControllerDelegate>{
    NSArray *_keyArray;
}
/**
 图片数组
 */
@property (nonatomic,strong)NSMutableArray *imgUrlArray;

@property (nonatomic,strong)TZImagePickerController *imagePickerVC;

/**
 问题描述
 */
@property (nonatomic,copy)NSString *questionDescription;

/**
 服务态度
 */
@property (nonatomic,copy)NSString *serviceScore;

/**
 维修品质
 */
@property (nonatomic,copy)NSString *repairScore;

@end

@implementation OrderScoreServiceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createMainView];
}

- (void)createMainView{
    self.title = @"订单详情";
    _keyArray = @[@"服务态度",@"维修品质"];
    AutoWeakSelf
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).offset(NAVIGATION_BAR_HEIGHT);
        make.left.right.equalTo(weakSelf.view);
        make.height.mas_equalTo(F_DEVICE_H - NAVIGATION_BAR_HEIGHT - bottomPadding(0));
    }];
    [self.tableView registerClass:[OneKeyRepairUploadImageTableCell class] forCellReuseIdentifier:UploadImageCellIdentifier];
    [self.tableView registerClass:[OneKeyRepairQuestionDescriptionTableCell class] forCellReuseIdentifier:QuestionCellIdentifier];
    [self.tableView registerClass:[OrderScoreStarTableViewCell class] forCellReuseIdentifier:StarCellIdentifier];
    self.imagePickerVC = [[TZImagePickerController alloc]initWithMaxImagesCount:6 delegate:self];
    self.imagePickerVC.allowTakePicture = YES;
}

- (void)serviceButtonAction{
    if (k_Is_Empty(self.serviceScore) || [self.serviceScore isEqualToString:@"0分"]) {
        [self showErrorTipWithTitle:@"请对服务态度评价"];
        return;
    }
    if (k_Is_Empty(self.repairScore) || [self.repairScore isEqualToString:@"0分"]) {
        [self showErrorTipWithTitle:@"请对维修品质评价"];
        return;
    }
    if (k_Is_Empty(self.questionDescription)) {
        [self showErrorTipWithTitle:@"请写下您的评价"];
        return;
    }
    if (!k_Is_Empty(self.serviceScore)) {
        self.serviceScore = [self.serviceScore substringToIndex:self.serviceScore.length - 1];
    }
    if (!k_Is_Empty(self.repairScore)) {
        self.repairScore = [self.repairScore substringToIndex:self.repairScore.length - 1];
    }
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:K_UserDefault_Read(CustomerUserID)?:@"" forKey:@"member_id"];
    [dict setObject:K_UserDefault_Read(CustomerUserToken)?:@"" forKey:@"member_token"];
    [dict setObject:self.order_id?:@"" forKey:@"order_id"];
    [dict setObject:self.serviceScore?:@"" forKey:@"assessment_star1"];
    [dict setObject:self.repairScore?:@"" forKey:@"assessment_star2"];
    [dict setObject:self.questionDescription?:@"" forKey:@"assessment_desc"];
    [dict setObject:[self.imgUrlArray componentsJoinedByString:@","]?:@"" forKey:@"assessment_imgs"];
    AutoWeakSelf
    [[QYNetManager sharedManager]POST:kInsertMaintailOrderAssessment parameters:dict andApiTyp:CustomerApiTypGetOrders SuccessBlock:^(id responseObject) {
        if ([responseObject[@"status"] isEqualToString:@"ok"]) {
            if ([responseObject[@"data"] integerValue]) {
                [weakSelf showTipWithTitle:@"评价成功"];
                NSArray *subViews = self.navigationController.viewControllers;
                for (BaseViewController *baseVC in subViews) {
                    if ([baseVC isKindOfClass:[MyOrderDetailViewController class]]) {
                        baseVC.isPop = YES;
                        baseVC.popArray = @[weakSelf.order_id?:@""];
                        [self.navigationController popToViewController:baseVC animated:YES];
                    }else if ([baseVC isKindOfClass:[MyOrderBaseViewController class]]){
                        baseVC.isPop = YES;
                        baseVC.popArray = @[[NSString stringWithFormat:@"%ld",weakSelf.viewTag]];
                        [self.navigationController popToRootViewControllerAnimated:YES];
                    }else if ([baseVC isKindOfClass:[MyOrderSearchViewController class]]){
                        baseVC.isPop = YES;
                        baseVC.popArray = @[self.keyword?:@""];
                        [self.navigationController popToViewController:baseVC animated:YES];
                    }
                }
            }else{
                [weakSelf showErrorTipWithTitle:@"评价失败\n请重试"];
            }
        }else{
            [weakSelf showErrorTipWithTitle:@"评价失败\n请重试"];
        }
    } Failure:^(NSError *error) {
        [weakSelf showErrorTipWithTitle:@"评价失败\n请重试"];
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1){
        if (indexPath.row == 1) {//维修拍照
            OneKeyRepairUploadImageTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:UploadImageCellIdentifier];
            cell.delegate = self;
            cell.dataSource = self.imgUrlArray;
            return cell;
        }else{//报修问题详情
            OneKeyRepairQuestionDescriptionTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:QuestionCellIdentifier];
            cell.textView.delegate = self;
            cell.textView.text = self.questionDescription?:QuestionPlaceholder;
            return cell;
        }
    }else{
        OrderScoreStarTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:StarCellIdentifier];
        cell.indexPath = indexPath;
        cell.nameLabel.text = _keyArray[indexPath.row];
        if (indexPath.row == 1) {
            [cell cellForRemarkFrame];
        }
        AutoWeakSelf
        cell.scoreBlock = ^(NSIndexPath * _Nonnull indexPath, NSString * _Nonnull score) {
            if (indexPath.row == 0) {
                weakSelf.serviceScore = score;
            }else{
                weakSelf.repairScore = score;
            }
        };
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            return 150;
        }else{
            return 100;
        }
    }
    return 40;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 35;
    }else{
        return 100;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView  *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, F_DEVICE_W, 35)];
    backView.backgroundColor = [UIColor appColor];
    if (section == 1) {
        backView.frame = CGRectMake(0, 0, F_DEVICE_W, 100);
        UIView *whiteView = [[UIView alloc]initWithFrame:CGRectMake(0, 50, F_DEVICE_W, 50)];
        whiteView.backgroundColor = [UIColor whiteColor];
        [backView addSubview:whiteView];
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, F_DEVICE_W - 30, 50)];
        titleLabel.text = @"评价内容";
        titleLabel.textColor = [HSPublic colorWithHexString:@"#666666"];
        titleLabel.font = Font28;
        [whiteView addSubview:titleLabel];
    }
    return backView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 1) {
        return 150;
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section == 1) {
        UIView  *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, F_DEVICE_W, 150)];
        backView.backgroundColor = [UIColor appColor];
        UIButton *serviceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [serviceBtn setTitle:@"评价服务" forState:UIControlStateNormal];
        [serviceBtn setTitle:@"评价服务" forState:UIControlStateSelected];
        [serviceBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [serviceBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        [serviceBtn setBackgroundColor:[HSPublic colorWithHexString:@"#333333"]];
        serviceBtn.layer.cornerRadius = 10;
        serviceBtn.layer.masksToBounds = YES;
        [backView addSubview:serviceBtn];
        [serviceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(backView).offset(30);
            make.top.equalTo(backView).offset(50);
            make.size.mas_equalTo(CGSizeMake(F_DEVICE_W - 60, 50));
        }];
        [serviceBtn addTarget:self action:@selector(serviceButtonAction) forControlEvents:UIControlEventTouchUpInside];
        return backView;
    }
    return nil;
}

#pragma mark - OneKeyRepairUploadImageTableCellDelegate
- (void)uploadImageTableCellAddImage:(NSIndexPath *)indexPath{
    
    AutoWeakSelf
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"评论照片" preferredStyle:UIAlertControllerStyleActionSheet];
    [alertController addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [weakSelf presentImageVC];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf presentImageVC];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf dismissViewControllerAnimated:YES completion:nil];
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
    
}

- (void)presentImageVC{
    AutoWeakSelf
    [self.imagePickerVC setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        __block typeof(weakSelf) strongSelf = weakSelf;
        NSString *urlStr = [NSString stringWithFormat:@"%@%@",kServiceID,kUploadRepairImage];
        [strongSelf showLoading];
        [[QYNetManager sharedManager]upLoadImageWithURL:urlStr parameters:nil andImageInfoArr:@[photos,assets] SuccessBlock:^(id responseObject) {
            [strongSelf hideLoading];
            if ([responseObject[@"status"] isEqualToString:@"ok"]) {
                NSArray *imgUrl = responseObject[@"data"];
                strongSelf.imgUrlArray = [NSMutableArray arrayWithArray:imgUrl];
                [strongSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:1]] withRowAnimation:UITableViewRowAnimationAutomatic];
            }else{
                [strongSelf showTipWithTitle:responseObject[@"error"]];
            }
        } Failure:^(NSError *error) {
            [strongSelf hideLoading];
            [strongSelf showErrorTipWithTitle:CustomerPoolNetStr];
        }];
    }];
    [self presentViewController:self.imagePickerVC animated:YES completion:nil];
}

- (void)uploadImageTableCellTapHaveALook:(NSIndexPath *)indexPath{
    HSImageScrollViewController *scrollVC = [[HSImageScrollViewController alloc]init];
    scrollVC.imgUrlArr = self.imgUrlArray;
    scrollVC.index = indexPath.row;
    [self.navigationController presentViewController:scrollVC animated:YES completion:nil];
}

#pragma mark - UITextViewDelegate
- (void)textViewDidBeginEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:QuestionPlaceholder]) {
        textView.text = @"";
        textView.textColor = [HSPublic colorWithHexString:@"333333"];
    }else{
        textView.textColor = [HSPublic colorWithHexString:@"#808080"];
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:@""]) {
        textView.text = QuestionPlaceholder;
        textView.textColor = [HSPublic colorWithHexString:@"#808080"];
    }else{
        textView.textColor = [HSPublic colorWithHexString:@"333333"];
        self.questionDescription = textView.text;
    }
}

- (NSMutableArray *)imgUrlArray{
    if (!_imgUrlArray) {
        _imgUrlArray = [NSMutableArray array];
    }
    return _imgUrlArray;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
